package demo.dao;

import jdbc.DBUtil;
import jdbc.UserInfo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserMapper {
    // 插入数据
    public int insert(UserInfo userInfo){
        try (Connection con = DBUtil.getConnection()) {
            PreparedStatement ps = con.prepareStatement(
                    "INSERT INTO userinfo(username,password,nickname,age) " +
                            "VALUES(?,?,?,?)"
            );
            ps.setString(1,userInfo.getUsername());
            ps.setString(2,userInfo.getPassword());
            ps.setString(3,userInfo.getNickname());
            ps.setInt(4,userInfo.getAge());
            return ps.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }
        return 0;
    }
    // 根据用户名查询用户信息
    public UserInfo findByUsername(String username){
        try (Connection con = DBUtil.getConnection()) {
            PreparedStatement ps = con.prepareStatement(
                    "SELECT username,password,nickname,age " +
                            "FROM userinfo " +
                            "WHERE username = ?"
            );
            ps.setString(1,username);
            ResultSet rs = ps.executeQuery();
            if (rs.next()){
                UserInfo userInfo = new UserInfo();//创建一个UserInfo对象
                userInfo.setUsername(rs.getString("username"));//将查询结果封装到UserInfo对象中
                userInfo.setPassword(rs.getString("password"));
                userInfo.setNickname(rs.getString("nickname"));
                userInfo.setAge(rs.getInt("age"));
                return userInfo;//返回UserInfo对象
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return null;
    }
    // 修改用户信息
    public int update(UserInfo userInfo){
        try (Connection con = DBUtil.getConnection()) {
            PreparedStatement ps = con.prepareStatement("" +
                    "UPDATE userinfo " +
                    "SET password = ?,nickname = ?,age = ? " +
                    "WHERE username = ?"
            );
            ps.setString(1,userInfo.getPassword());
            ps.setString(2,userInfo.getNickname());
            ps.setInt(3,userInfo.getAge());
            ps.setString(4,userInfo.getUsername());
            return ps.executeUpdate();

        }catch (SQLException e){
            e.printStackTrace();
        }
        return 0;
    }
}
